package top.went.service;

import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.went.db.dao.DemandDao;
import top.went.db.dao.PurchaseDao;
import top.went.db.dao.ReturnGoodsDao;
import top.went.db.dao.ReturnGoodsDetailDao;
import top.went.db.mapper.ReturnGoodsDetailMapper;
import top.went.exception.NotFoundException;
import top.went.exception.ServiceException;
import top.went.pojo.*;
import top.went.vo.OrderDetail;
import top.went.vo.PageEntity;
import top.went.vo.PurchaseDetailVO;
import top.went.vo.ReturnGoodsDetailVo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(value = "transactionManager",rollbackFor = ServiceException.class)
public class ReturnGoodsDetailService {
    @Autowired
    private ReturnGoodsDetailDao returnGoodsDetailDao;
    @Autowired
    private ReturnGoodsDetailMapper returnGoodsDetailMapper;
    @Autowired
    private ReturnGoodsService returnGoodsService;
    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private PurchaseDao purchaseDao;
    @Autowired
    private OrderService orderService;

    private static final Map<String,String> map=new HashMap<>();
    static {
        map.put("rgdNum", "rgd_num");
        map.put("rgdMoney", "rgd_money");
        map.put("rgdOutwhNum", "rgd_outwh_num");
    }
    /**
     * 添加退货明细
     * @param returnGoodsDetailEntity
     * @throws ServiceException
     */
    public boolean rgd_insert(ReturnGoodsDetailEntity returnGoodsDetailEntity)throws ServiceException{
        try {
            if (returnGoodsDetailEntity.getTbReturnGoodsByRgId() != null && returnGoodsDetailEntity.getTbReturnGoodsByRgId() .getRgId()!=null){}
            else
                returnGoodsDetailEntity.setTbReturnGoodsByRgId(null);
            if (returnGoodsDetailEntity.getPurDetailEntity()!= null && returnGoodsDetailEntity.getPurDetailEntity().getPdId()!=null){}
            else
                returnGoodsDetailEntity.setPurDetailEntity(null);
            if(returnGoodsDetailEntity.getTbProductFormatByPfId()!=null&&returnGoodsDetailEntity.getTbProductFormatByPfId().getPfId()!=null){}
            else
                returnGoodsDetailEntity.setTbProductFormatByPfId(null);
            returnGoodsDetailEntity.setMagicDelete(0l);
            returnGoodsDetailEntity.setRgdOutwhNum(0);
            return returnGoodsDetailDao.save(returnGoodsDetailEntity)!= null;
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("新建退货明细失败");
        }
    }

    /**
     * 删除退货明细
     * @param rgdId
     * @throws ServiceException
     */
    public boolean rgd_logicDelete(int rgdId)throws ServiceException,NotFoundException {
        ReturnGoodsDetailEntity returnGoodsDetailEntity=load(rgdId);
        if(returnGoodsDetailEntity==null)
            throw new NotFoundException("不存在该退货明细");
        if (!returnGoodsDetailEntity.getTbReturnGoodsByRgId().getRgState().equals("待处理"))
            throw new ServiceException("该退货单已经完成");
        try {
            returnGoodsDetailEntity.setMagicDelete(1l);
            return returnGoodsDetailDao.save(returnGoodsDetailEntity)!=null;
        }catch (Exception e){
            e.printStackTrace();
            throw  new ServiceException("删除该退货明细");
        }
    }
    /**
     * 批量删除退货明细
     * @param ids
     * @throws ServiceException
     */
    public boolean pd_logicDeleteAll(Long[] ids)throws ServiceException,NotFoundException {
        for (int i = 0; i < ids.length; i++) {
            rgd_logicDelete(ids[i].intValue());
        }
        return true;
    }

    /**
     * 查询退货明细
     * @return
     */
    public PageEntity<ReturnGoodsDetailVo> rgd_findAll(Integer pageSize, Integer pageNumber) throws ServiceException{
        try {
            List<ReturnGoodsDetailEntity> rows =returnGoodsDetailDao.findAllByMagicDeleteOrderByRgdId(0l, new PageRequest(pageNumber,pageSize));
            int total=returnGoodsDetailDao.rgd_findAllCount();
            return new PageEntity<ReturnGoodsDetailVo>((long) total, getReturnGoodsDetailVo(rows));
        }catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("查询所有退货明细失败");
        }
    }


    /**
     * 高级查询
     * @param returnGoodsDetailVo
     * @return
     * @throws ServiceException
     */
    public PageEntity<ReturnGoodsDetailVo> findAllByManyConditions(ReturnGoodsDetailVo returnGoodsDetailVo) {
        if(returnGoodsDetailVo==null)
            return new PageEntity<>(0l, null);
        String order =returnGoodsDetailVo.getPage().getSort(map);
        if(order.length()<=0)
            order = "rgd_id desc";
        com.github.pagehelper.Page<PurDetailEntity> page1 = PageHelper.startPage(returnGoodsDetailVo.getPage().getPage(), returnGoodsDetailVo.getPage().getSize(), order+" nulls last");
        returnGoodsDetailMapper.findByManyCondition(returnGoodsDetailVo);
        return new PageEntity(page1.getTotal(), page1.getResult());
    }
    /**
     * 加载退货明细
     * @param rgdId
     * @return
     * @throws ServiceException
     */
    public ReturnGoodsDetailVo load1(Integer rgdId) throws ServiceException{
        try {
            return getReturnGoodsDetailVo1(returnGoodsDetailDao.findAllByMagicDeleteAndRgdId(0l, rgdId));
        }catch (Exception e){
            e.printStackTrace();;
            throw new ServiceException("加载退货明细失败");
        }
    }
    /**
     * 加载退货明细
     * @param rgdId
     * @return
     * @throws ServiceException
     */
    public ReturnGoodsDetailEntity load(Integer rgdId) throws ServiceException{
        ReturnGoodsDetailEntity returnGoodsDetailEntity = returnGoodsDetailDao.findAllByMagicDeleteAndRgdId(0l, rgdId);
        if (returnGoodsDetailEntity == null)
            throw new ServiceException("明细不存在");
        return returnGoodsDetailEntity;

    }

    /**
     *将采购明细转退货明细
     * @param rgId
     * @param purId
     * @return
     * @throws ServiceException
     */
    public boolean loadAll(int rgId, Integer purId) throws ServiceException, NotFoundException {
        PurchaseDetailVO purchaseDetailVO = new PurchaseDetailVO();
        java.util.List<PurDetailEntity> purDetailEntities = new ArrayList<>();
        List<ReturnGoodsDetailVo> returnGoodsDetailVos = new ArrayList<>();
        if (purId == null)
            throw new ServiceException("信息错误");
        purchaseDetailVO.setPurId(purId);
        purDetailEntities = purchaseDetailService.findAllByManyConditions(purchaseDetailVO).getRows();

        for (PurDetailEntity purDetailEntity : purDetailEntities) {
            ReturnGoodsDetailEntity returnGoodsDetailEntity = new ReturnGoodsDetailEntity();
            returnGoodsDetailEntity.setTbReturnGoodsByRgId(returnGoodsService.load(rgId));
            returnGoodsDetailEntity.setTbProductFormatByPfId(purDetailEntity.getTbProductFormatByPfId());
            returnGoodsDetailEntity.setPurDetailEntity(purDetailEntity);
            returnGoodsDetailEntity.setTbProductFormatByPfId(purDetailEntity.getTbProductFormatByPfId());
            returnGoodsDetailEntity.setTbProductByProductId(purDetailEntity.getTbProductByProductId());
            returnGoodsDetailEntity.setRgdNum((long) purchaseDao.inCount(purDetailEntity.getTbPurchaseByPurId().getPurId(),purDetailEntity.getTbProductFormatByPfId().getPfId()));
            returnGoodsDetailEntity.setRgdMoney(Double.valueOf(purDetailEntity.getPdTotal().toString()));
            rgd_insert(returnGoodsDetailEntity);
        }
        return true;
    }
    /**
     *将订单明细转退货明细
     * @param rgId
     * @param order
     * @return
     * @throws ServiceException
     */
    public boolean orderToRg(int rgId, Integer order) throws ServiceException, NotFoundException {
        ReturnGoodsEntity returnGoodsEntity = returnGoodsService.load(rgId);
        List<OrderDetail> orderDetails = orderService.loadDeatil(order.longValue());
        System.out.println("订单"+order);
        orderDetails.removeIf(orderDetail -> orderService.getSendNum(order,
                orderDetail.getFormatterId().intValue()) <=0);
        if (orderDetails.size()<=0)
            throw new ServiceException("没有需要退货的产品");
        for (OrderDetail orderDetail : orderDetails) {
            ReturnGoodsDetailEntity returnGoodsDetailEntity = new ReturnGoodsDetailEntity(
                    orderService.getSendNum(order,
                            orderDetail.getFormatterId().intValue()),orderDetail.getTotal().doubleValue(),
                    0,0L,returnGoodsEntity,orderDetail.getFormatEntity()
            );
           rgd_insert(returnGoodsDetailEntity);
        }
        return true;
    }
    /**
     * 根据退货id查询退货明细
     * @param id
     * @return
     */
   public List<ReturnGoodsDetailVo> findAll(Integer id){
       ReturnGoodsDetailVo returnGoodsDetailVo =new ReturnGoodsDetailVo();
       returnGoodsDetailVo.setRgId(id);
       return findAllByManyConditions(returnGoodsDetailVo).getRows();
   };

    private List<ReturnGoodsDetailVo> getReturnGoodsDetailVo(List<ReturnGoodsDetailEntity> returnGoodsDetailEntities){
        List<ReturnGoodsDetailVo> returnGoodsDetailVos=new ArrayList<>();
        for(ReturnGoodsDetailEntity returnGoodsDetailEntity:returnGoodsDetailEntities){
            returnGoodsDetailVos.add(new ReturnGoodsDetailVo(returnGoodsDetailEntity));
        }
        return returnGoodsDetailVos;
    }
    private ReturnGoodsDetailVo getReturnGoodsDetailVo1(ReturnGoodsDetailEntity returnGoodsDetailEntity){
        ReturnGoodsDetailVo returnGoodsDetailVo=new ReturnGoodsDetailVo(returnGoodsDetailEntity);
        return returnGoodsDetailVo;
    }
    /**
     * 添加退货单明细
     * @param returnGoodsDetailEntities
     * @return
     */
    public boolean addDetail(List<ReturnGoodsDetailEntity> returnGoodsDetailEntities, Long id) throws NotFoundException, ServiceException {
        ReturnGoodsEntity returnGoodsEntity = returnGoodsService.load(Math.toIntExact(id));
        for(ReturnGoodsDetailEntity returnGoodsDetailEntity1:returnGoodsDetailEntities){
            returnGoodsDetailEntity1.setTbReturnGoodsByRgId(returnGoodsEntity);
            rgd_insert(returnGoodsDetailEntity1);
        }
        return true;
    }

    /**
     * 修改退货单明细数据
     * @param returnGoodsDetailEntities
     */
    public void modifyDetail(List<ReturnGoodsDetailEntity> returnGoodsDetailEntities) throws ServiceException {
            if (returnGoodsDetailEntities == null)
                throw new ServiceException("明细数据错误");
        try {
            for (ReturnGoodsDetailEntity returnGoodsDetailEntity : returnGoodsDetailEntities) {
                if (returnGoodsDetailEntity.getRgdNum() <=0)
                    throw new ServiceException("请选择删除明细");
                ReturnGoodsDetailEntity r = load(returnGoodsDetailEntity.getRgdId());
                if (returnGoodsDetailEntity.getRgdNum() > r.getRgdNum())
                    throw new ServiceException("退货明细数量不能大于入库明细");
                if (r.getRgdMoney() != null)
                    r.setRgdMoney((r.getRgdMoney()/r.getRgdNum())*returnGoodsDetailEntity.getRgdNum());

                r.setRgdNum(returnGoodsDetailEntity.getRgdNum());

                r.setRgdReason(returnGoodsDetailEntity.getRgdReason());
                r.setRgdRemarks(returnGoodsDetailEntity.getRgdRemarks());
                returnGoodsDetailDao.save(r);
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 加载退货明细
     * @param rgId
     * @param type
     * @return
     */
    public List<ReturnGoodsDetailVo> loadDetails(Integer rgId,Integer type) {
        return  returnGoodsDetailMapper.loadDetails(rgId,type);
    }
}

